import { Provide,httpError } from '@midwayjs/core';
import { Repository } from 'typeorm';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { user } from '../entity/user.entity';
import { is_wgj } from '../entity/is_wgj.entity';
import { UserDto,UpdateUserDto} from '../dto/userDto';

@Provide()
export class UserDao {

  @InjectEntityModel(user)
  userModel: Repository<user>;

  @InjectEntityModel(is_wgj)
  isWgjModel: Repository<is_wgj>;

  //查找用户
  async getUser(userId: UserDto['user_id']): Promise<user | null> {
    return await this.userModel.findOne({
      where:{ user_id:userId },
      select: [
        'user_id',
        'account',
        'name', 
        'email', 
        'valid_flag', 
        'create_time',
        'password']
    });
  }
  //用account查找用户
  async getUserByAccount(account: UserDto['account']): Promise<user | null> {
    return await this.userModel.findOne({
      where:{ account:account },
      select: ['user_id', 
        'account', 
        'name', 
        'email',
        'valid_flag',
        'create_time',
        'password']
    });
  }

  //查找用户是不是wgj
  async isWgj(userId:UserDto['user_id']){
    //表连接
    const user = await this.userModel.createQueryBuilder('user')
      .leftJoinAndSelect('user.is_wgj', 'is_wgj')
      .where('user.user_id = :userId', { userId })
      .select([
      'user.user_id', 
      'user.account',
      'user.name',
      'user.email',
      'user.valid_flag',
      'user.create_time',
      'is_wgj.is_wgjId',
      'is_wgj.is_wgj'])
      .getMany();
    return user;
  }

  //更新用户数据
  async updateUser(userId: UpdateUserDto['user_id'], userData: UpdateUserDto): Promise<user> {

    //查询用户数据
    const user = await this.userModel.findOneBy({ user_id: userId });
    if (!user) {
      throw new httpError.NotFoundError('User not found');
    }

    //浅拷贝，只更新用户数据
    Object.assign(user, userData);
    return await this.userModel.save(user);
  }
}
